import requests
from utils.csv_utils import get_ips


def get_auth(zabbix_url, headers, username, password):
    login_payload = {
        "jsonrpc": "2.0",
        "method": "user.login",
        "params": {
            "username": username,
            "password": password
        },
        "id": 1
    }
    response = requests.post(zabbix_url, headers=headers, json=login_payload)
    auth_token = response.json().get('result')
    # print("Auth token:", auth_token)

    return auth_token


def get_hosts(zabbix_url, headers, auth_token, host):
    get_hosts_payload = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "selectTags": ["tag", "value"],
            "output": ["hostid", "host", "name", "tags"],
            "filter": {
                "host": [
                    host
                ]
            }
        },
        "auth": auth_token,
        "id": 2
    }

    response = requests.post(zabbix_url, headers=headers, json=get_hosts_payload)
    hosts = response.json().get('result')
    if len(hosts) == 0:
        # print(f'warning: fails get_hosts. host: {host}')
        return None

    return hosts

def get_hosts_from_group(zabbix_url, headers, auth_token, group):
    get_hosts_payload = {
        "jsonrpc": "2.0",
        "method": "host.get",
        "params": {
            "output": ["hostid", "host", "name"],
            "filter": {
                "group": [
                    group
                ]
            }
        },
        "auth": auth_token,
        "id": 2
    }

    response = requests.post(zabbix_url, headers=headers, json=get_hosts_payload)
    hosts = response.json().get('result')
    return hosts

def update_hosts(zabbix_url, headers, auth_token, hostid, tags: list):
    update_hosts_payload = {
        "jsonrpc": "2.0",
        "method": "host.update",
        "params": {
            "hostid": int(hostid),
            "tags": [
                {
                "tag": tags[0],
                "value": tags[1]
                },
                # 这里可以添加多个标签，但之前的标签会被覆盖。
                # {
                #     "tag": 'aaa',
                #     "value": tags[3]
                # }
            ]
        },
        "auth": auth_token,
        "id": 1
    }
    r = requests.post(zabbix_url, headers=headers, json=update_hosts_payload)
    print(r.json())


def logout(zabbix_url, headers, auth_token):
    logout_payload = {
        "jsonrpc": "2.0",
        "method": "user.logout",
        "params": [],
        "auth": auth_token,
        "id": 3
    }

    requests.post(zabbix_url, headers=headers, json=logout_payload)
    # print("Logged out successfully.")

def get_token(zabbix_url, headers, username, password):
    auth_token = get_auth(zabbix_url, headers, username, password)

    return auth_token

def update_tags_for_group():
    zabbix_url = "http://10.104.14.27/api_jsonrpc.php"
    username = "Admin"
    password = "zabbix"
    headers = {"Content-Type": "application/json-rpc"}

    auth_token = get_auth(zabbix_url, headers, username, password)

    api_hosts = get_hosts_from_group(zabbix_url, headers, auth_token, "有线网段")
    ips = get_ips(f'e:\\important_tags_for_zabbix.csv')
    for a_host in api_hosts:
        ip = '.'.join(a_host['host'].split('.')[2:])
        switch_name = ips.get(ip)
        if switch_name:
            print(a_host['hostid'], switch_name, ip)
            update_hosts(zabbix_url, headers, auth_token, a_host['hostid'], ['类型', switch_name])

    logout(zabbix_url, headers, auth_token)

def update_tags_for_host():
    fail_ips_csv = []
    fail_ips_api = []
    zabbix_url = "http://10.104.14.27/api_jsonrpc.php"
    username = "Admin"
    password = "zabbix"
    headers = {"Content-Type": "application/json-rpc"}

    auth_token = get_auth(zabbix_url, headers, username, password)

    ips_csv = get_ips(f'e:\\important_tags_for_zabbix.csv')
    for ip_csv in ips_csv:
        search_ip = ''
        if '.' not in ip_csv:
            print(f'warning: "{ip_csv}" not is IP format.')
            fail_ips_csv.append(ip_csv)
            continue
        ip_csv_size = len(ip_csv.split('.'))
        if ip_csv_size == 4:
            search_ip = ip_csv
        elif ip_csv_size == 2:
            search_ip = '10.106.' + ip_csv

        api_hosts = get_hosts(zabbix_url, headers, auth_token, search_ip)
        if not api_hosts:
            # print(f'warning: not search host in zabbix. host: {search_ip}')
            fail_ips_api.append(search_ip)
            continue
        api_hosts = api_hosts[0]
        if ip_csv_size == 4:
            api_ip = '.'.join(api_hosts['host'].split('.'))
        elif ip_csv_size == 2:
            api_ip = '.'.join(api_hosts['host'].split('.')[2:])

        switch_name = ips_csv.get(api_ip)
        if switch_name:
            print(api_hosts['hostid'], switch_name, api_ip)
            update_hosts(zabbix_url, headers, auth_token, api_hosts['hostid'], ['类型', switch_name])
    
    if fail_ips_csv:
        for ip in fail_ips_csv:
            print(f'warning: "{ip}" not is IP format.')
    if fail_ips_api:
        for ip in fail_ips_api:
            print(f'warning: "{ip}" not search host in zabbix.')

    logout(zabbix_url, headers, auth_token)


def demo_get_host(host):
    zabbix_url = "http://10.104.14.27/api_jsonrpc.php"
    username = "Admin"
    password = "zabbix"
    headers = {"Content-Type": "application/json-rpc"}
    auth_token = get_token(zabbix_url, headers, username, password)
    host = get_hosts(zabbix_url, headers, auth_token, host)
    print(host == None)
    logout(zabbix_url, headers, auth_token)

    return host

# 添加简化的 get_hosts 函数供 grouping_notify.py 使用
def get_hosts_simple(host):
    """简化的主机获取函数，用于 grouping_notify.py"""
    zabbix_url = "http://10.104.14.27/api_jsonrpc.php"
    username = "Admin"
    password = "zabbix"
    headers = {"Content-Type": "application/json-rpc"}
    
    auth_token = get_auth(zabbix_url, headers, username, password)
    hosts = get_hosts(zabbix_url, headers, auth_token, host)
    logout(zabbix_url, headers, auth_token)
    
    return hosts

    
if __name__ == "__main__":
    update_tags_for_host()